/**
 * @file ellipsis-title.ts
 * @description Vue指令：当文本溢出时，返回true，否则返回false  配合ellipsis-label-common组件使用
 * @example
 * v-ellipsis-title="updateTooltip"
 */
import type { Directive } from 'vue'

export const ellipsisTitle: Directive = {
  mounted(el, binding) {
    const check = () => checkOverflow(el, binding)
    // 监听元素尺寸变化
    const observer = new ResizeObserver(check)
    observer.observe(el)
    ;(el as any)._observer = observer
    check()
  },
  updated(el, binding) {
    nextTick(() => checkOverflow(el, binding))
  },
  unmounted(el) {
    const observer = (el as any)._observer
    observer?.disconnect()
  }
}

function checkOverflow(el: HTMLElement, binding: any) {
  if (el.scrollWidth > el.clientWidth) {
    if (binding.value && typeof binding.value === 'function') {
      binding.value(true)
    }
  } else {
    if (binding.value && typeof binding.value === 'function') {
      binding.value(false)
    }
  }
}

/**
 * @file ellipsis-title.ts
 * @description Vue指令：当文本溢出时，给标签添加title属性，否则移除title属性
 * @example
 * v-ellipsis-title
 */

// 直接使用指令 添加title属性
export const ellipsisTitleNative: Directive = {
  mounted(el) {
    // 等待渲染后再判断
    setTitle(el)
  },
  updated(el) {
    setTitle(el)
  }
}

function setTitle(el: HTMLElement) {
  // 只判断单行溢出
  if (el.scrollWidth > el.clientWidth) {
    el.setAttribute('title', el.textContent || '')
  } else {
    el.removeAttribute('title')
  }
}
